package com.lyf.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateUtil {

    public static final String YMD = "yyyyMMdd";
    public static final String Y_M_D = "yyyy-MM-dd";
    public static final String Y_M = "yyyy-MM";
    public static final String Y_M_1 = "yyyy-MM-01";

    public static Date format(String format) {
        SimpleDateFormat dayFormat = new SimpleDateFormat(format);
        try {
            return dayFormat.parse(dayFormat.format(new Date()));
        } catch (ParseException e) {
            return null;
        }
    }

    public static String formatString(String format) {
        return formatString(new Date(), format);
    }

    public static String now() {
        return formatString(new Date(), Y_M_D);
    }

    public static String now(String fmt) {
        return formatString(new Date(), fmt);
    }

    public static String formatString(Date date, String format) {
        SimpleDateFormat dayFormat = new SimpleDateFormat(format);
        return dayFormat.format(date);
    }

    public static int formatInt(String format) {
        SimpleDateFormat dayFormat = new SimpleDateFormat(format);
        return Integer.parseInt(dayFormat.format(new Date()));
    }

    public static String calDate(Date date, int index, int field, String format) {
        TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
        TimeZone.setDefault(tz);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(field, index);
        return formatString(calendar.getTime(), format);
    }

    /**
     * 计算出距今指定间隔的月份, 正数向前, 负数向后
     * @param date
     * @param index
     * @param format
     * @return
     */
    public static String calMonthDate(Date date, int index, String format) {
        return calDate(date, index, Calendar.MONTH, format);
    }

    /**
     * 计算出距今指定间隔的日期, 正数向前, 负数向后
     * @param date
     * @param index
     * @param format
     * @return
     */
    public static String calDayDate(Date date, int index, String format) {
        return calDate(date, index, Calendar.DATE, format);
    }

}
